import streamlit as st
from data_display.bar_chart import BarChart
from data_display.word_cloud import WordCloud
from data_display.line_chart import LineChart
import pickle
import os

def render_dashboard():
    st.title('海关报关数据展示平台')
    render_chart('词云', 'word_cloud', WordCloud.plot, ['日', '周', '月', '年'], 3)
    render_chart('柱状图', 'bar_chart', BarChart.plot, ['日', '周', '月', '年'], 3)
    render_chart('折线图', 'line_chart', LineChart.plot, ['周', '月', '年'], 2)
    try:
    # 尝试从文件中读取进程的PID
        with open("D:/robotlearn/agent/app_process.pid", "rb") as f:
            pid = pickle.load(f)
    except FileNotFoundError:
        st.warning("无法获取进程信息，可能无法正常终止应用。")
        pid = None

    if st.button("终止应用"):
        if pid is not None:
            if os.name == 'nt':  # Windows系统
                try:
                    os.system(f"taskkill /F /PID {pid}")
                    st.success("应用已成功终止。")
                    os.remove("D:/robotlearn/agent/app_process.pid")
                except Exception as e:
                    st.error(f"终止应用失败：{e}")
        else:
            st.warning("没有有效的进程信息，无法终止应用。")

def render_chart(title, chart_key, plot_func, time_options, default_index=0):
    st.header(title)
    time_range = st.selectbox(f'选择{title}时间范围', time_options, default_index)
    update_chart(chart_key, plot_func, time_range)
    display_chart(chart_key)

def update_chart(chart_key, plot_func, time_range):
    if st.session_state.get(f'last_{chart_key}_time_range') == time_range:
        return
    st.session_state[f'last_{chart_key}_time_range'] = time_range
    st.session_state[chart_key] = plot_func(time_range)

def display_chart(chart_key):
    if chart_key == 'word_cloud':
        st.markdown(f'<div>{st.session_state[chart_key]}</div>', unsafe_allow_html=True)
    else:
        st.altair_chart(st.session_state[chart_key], use_container_width=True)
